
import 'dart:convert';
import 'package:flutter_logger_server/utils/log_utils.dart';
import 'package:flutter_logger_server/beans/request_bean.dart';
import 'package:flutter_logger_server/beans/response_bean.dart';
import 'package:flutter_logger_server/flutter_logger_server.dart';
import 'dart:async';
class HttpLoggerPlugin {
  final List<RequestBean> _requestBeans = [];
  final List<ResponseBean> _responseBeans = [];
  Timer? _timer;
  void sendHttpReq({String? id,DateTime? createTime, String? url, String? method, Map<String, dynamic>? headers, String? body, }) {
    if (!FlutterLoggerServer.instance.isStarted){
      LogUtils.log("没有初始化，无法发送消息");
      return;
    }
    RequestBean requestBean = RequestBean(id: id, url: url, method: method, createTime: createTime, headers: headers, body: body);
    _requestBeans.add(requestBean);
  }


  void sendHttpRes({String? id,  DateTime? createTime, int? statusCode, Map<String, dynamic>? headers, String? body, String? statusReason } ) {
    if (!FlutterLoggerServer.instance.isStarted){
      LogUtils.log("没有初始化，无法发送消息");
      return;
    }
    RequestBean? findRequestBean;
    //判断如果id相同，则通过websocket发送消息，否则保存到list
    for (RequestBean requestBean in _requestBeans) {  
      if (requestBean.id == id) {
        //通过websocket发送消息
        findRequestBean = requestBean;
      }
    }
    ResponseBean responseBean = ResponseBean(id: id, statusCode: statusCode, headers: headers, body: body, createTime: createTime, statusReason: statusReason);
    if (findRequestBean==null) {
      LogUtils.log("没有找到请求信息，保存到list");
      _responseBeans.add(responseBean);
    }else{
      var messageData = jsonEncode({
        "request": findRequestBean.toJson(),
        "response": responseBean.toJson(),
      });
      LogUtils.log("发送消息");

      FlutterLoggerServer.instance.webSocketUtils.postMessage("http_log", messageData);
      _requestBeans.remove(findRequestBean);
    }
  }

  void init() {
    _requestBeans.clear();
    _responseBeans.clear();
    _timer = Timer.periodic(const Duration(seconds: 10), (timer) {
      for (RequestBean requestBean in _requestBeans) {
        if(requestBean.createTime==null){
           _requestBeans.remove(requestBean);
           LogUtils.log("移除请求信息:${requestBean.toJson()}");
           continue;
        }
        if (requestBean.createTime?.isBefore(DateTime.now().subtract(const Duration(minutes: 2))) ?? false) {
          _requestBeans.remove(requestBean);
          LogUtils.log("移除请求信息:${requestBean.toJson()}");
        }
      }
      for (ResponseBean responseBean in _responseBeans) {
        if (responseBean.createTime == null) {
          _responseBeans.remove(responseBean);
          LogUtils.log("移除响应信息:${responseBean.toJson()}");
          continue;
        }
        if (responseBean.createTime?.isBefore(
            DateTime.now().subtract(const Duration(minutes: 2))) ?? false) {
          _responseBeans.remove(responseBean);
          LogUtils.log("移除响应信息:${responseBean.toJson()}");
        }
      }
    });
  }

  void clear() {
    _timer?.cancel();
    _requestBeans.clear();
    _responseBeans.clear();
  }
}
